package com.example.learnapp;

import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import com.example.learnapp.Utils.H264Encoder;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Camera_Activity extends AppCompatActivity implements Camera.PreviewCallback {

    public Button mButton,h264;
    public Button switchBtn;
    private Camera mCamera;
    private SurfaceView surfaceView;
    private SurfaceHolder mSurfaceHolder;
    private int cameraId = 1;
    private boolean mIsSufaceCreated1 = false;
    private boolean video_type=true;
    int framerate = 15; //一秒30帧
    private H264Encoder encoder; //自定义的编码操作类

    private static int i=0;

    BufferedOutputStream bufferedOutputStream = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initView();
        initButton();
    }

    //视图初始化
    private void initView() {
        surfaceView = findViewById(R.id.surfaceView);//获得SurfaceView的实例
        mSurfaceHolder = surfaceView.getHolder();//获得SurfaceView的Holder
        mSurfaceHolder.addCallback(mSurfaceCallback);//设置Holder的回调

        try {
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+"test.yuv"));
        } catch (FileNotFoundException e) {
            e.printStackTrace( );
        }

    }

    private SurfaceHolder.Callback mSurfaceCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            mIsSufaceCreated1 = true;
        }
        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
            startPreview();//不自动回调预览
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            mIsSufaceCreated1 = false;
        }
    };


    //打开照相机
    public void startPreview() {
        try
        {
            //打开摄像机
            mCamera = Camera.open(cameraId);
            Camera.Parameters parameters = mCamera.getParameters();
            Camera.Size size = getBestPreviewSize(1080, 1920, parameters);
            if(size != null){
                parameters.setPreviewSize(size.width,size.height);
            }
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            parameters.setPreviewFrameRate(25);
            parameters.setPreviewFormat(ImageFormat.NV21); //设置数据格式
            parameters.setRecordingHint(true);
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewCallback(this);
            mCamera.setParameters(parameters);
            //绑定Surface并开启预览
            mCamera.setPreviewDisplay(mSurfaceHolder);
            mCamera.startPreview();
        } catch (IOException e) {
            mCamera.release();
            mCamera = null;
            Toast.makeText(this, "surface created failed", Toast.LENGTH_SHORT).show();
        }
    }

    private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
        Camera.Size result = null;

        for(Camera.Size size : parameters.getSupportedPreviewSizes()){

            Log.i("TAG" , "data="+size.width+"  "+size.height);
            if(size.width <= width && size.height <= height){
                if(result == null){
                    result = size;
                }else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;

                    if(newArea > resultArea){
                        result = size;
                    }
                }
            }
        }

        return result;
    }

    private  void stopPreview(){
        if(mCamera != null){
            try {
                mCamera.setPreviewDisplay(null);
            } catch (IOException e) {
                e.printStackTrace();
            }
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }
    //回调初始化
    private void initButton() {
        //返回上个界面的按钮
        mButton = findViewById(R.id.button2);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopPreview();
            }
        });
        //翻转摄像机的按钮
        switchBtn = findViewById(R.id.button3);
        switchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CameraSwitch();
            }
        });

        h264 = findViewById(R.id.h264);
        h264.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(video_type){
                    h264.setText("已开始 H624");
                    video_type=!video_type;
                    h264.setBackgroundColor(Color.rgb(0, 255, 0));
                    start_h264();
                }else{
                    h264.setText("结束 H624");
                    h264.setBackgroundColor(Color.rgb(255, 0, 0));
                    video_type=!video_type;
                    end_h264();

                }
            }
        });
    }

    //翻转摄像机
    public void CameraSwitch()
    {
        cameraId = cameraId == 1 ? 0 : 1;
        stopPreview();
        startPreview();
    }


    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        Log.i("TAG" , "data="+data.length);
        if (encoder != null) {
            encoder.putDate(data); //将一帧的数据传过去处理
        }

        try {
            i++;
            bufferedOutputStream.write(data);
        } catch (FileNotFoundException e) {
            e.printStackTrace( );
        } catch (IOException e) {
            e.printStackTrace( );
        }

    }

    public void start_h264(){
        Camera.Parameters parameters = mCamera.getParameters();
        Camera.Size size = parameters.getPreviewSize();
        encoder = new H264Encoder(size.width,size.height,framerate);
        encoder.startEncoder(); //开始编码
    }

    public void end_h264(){
        encoder.stopEncoder();
        try {
            bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace( );
        }

    }
}